<?php
// +----------------------------------------------------------------------
// | 京东收银
// +----------------------------------------------------------------------

namespace helper\jd;

use helper\jd\sdk\ConfigUtil;
use helper\jd\sdk\HttpUtils;
use helper\jd\sdk\XMLUtil;

class Pay
{
    private array $config;

    private string $host = "https://openapi.duolabao.com/";

    public function __construct($config)
    {
        $this->config = [
            //'merchant' => $config['merchant'],
            'notify_url' => $config['notify_url']
        ];
    }

    /**
     * 统一下单接口
     * @param string $subject
     * @param string $out_trade_no
     * @param float $total_amount
     * @return mixed
     */
    public function page(string $subject, string $out_trade_no, float $total_amount, string $return_url)
    {
        return $this->pay($subject, $out_trade_no, $total_amount, $return_url, 'ONLINE_PC');
    }

    public function wap(string $subject, string $out_trade_no, float $total_amount, string $return_url)
    {
        return $this->pay($subject, $out_trade_no, $total_amount, $return_url, 'ONLINE_APP');
    }

    public function pay(string $subject, string $out_trade_no, float $total_amount, string $return_url, $sceneType)
    {
        $body = [
            "version" => "V2.0",//版本号
            "merchant" => "110058979048",//商户号
            "payMerchant" => "",//收款商户
            "tradeNum" => $out_trade_no,//交易流水号
            "tradeName" => $subject,//交易名称
            "tradeDesc" => "",//
            "tradeTime" => date('YmdHis'),
            "amount" => $total_amount * 100,//交易金额 单位：分
            "orderType" => 1,//orderType 0-实物，1-虚拟
            "currency" => 'CNY',//货币种类
            "industryCategoryCode" => '',//业务类型
            "note" => '',// 商户备注
            "callbackUrl" => $return_url,//同步通知页面
            "notifyUrl" => $this->config["notify_url"],//异步通知页面地址
            "ip" => '',//用户 IP
            "tradeType" => 'AGGRE',//交易类型
            "sceneType" => $sceneType,//场景类型 ONLINE_APP：线上移动端支付,ONLINE_PC：线上 PC 端支付,OFFLINE：线下支付
            "expireTime" => 600,// 订单失效时长,单位秒
            "userId" => '',//用户唯一标识
            "goodsInfo" => '',//商品信息
            "termInfo" => '',//终端信息
            "riskInfo" => '',//风控信息
            "identity" => '',//指定支付信息
            "subAppId" => '',//商户 APPID
            "accessType" => '',//接入方式 sceneType=ONLINE_APP 且接入微信支付时必传
            "subOpenId" => '',//微信/支付宝用户标识
        ];

        $reqXmlStr = XMLUtil::encryptReqXml($body);
        $url = ConfigUtil::get_val_by_key("aggreUniorderUrl");
        $httputil = new HttpUtils();
        list ($return_code, $return_content) = $httputil->http_post_data($url, $reqXmlStr);
        $resData = [];
        $flag = XMLUtil::decryptResXml($return_content, $resData);
        if ($flag) {
            $code = $resData['result']['code'];
            if ($code == "000000") {
                $resData['respMsg'] = "调用聚合统一下单成功";
                header('Location: ' . $resData['returnUrl']);
                return true;
            } else{
                $resData['respMsg'] = $resData['result']['desc'];
            }
            return $resData;
        } else {
            return false;
        }
    }

    /**
     * 查询
     * @return array
     */
    public function query($tradeNum)
    {
        $param["version"] = "V2.0";
        $param["merchant"] = $this->config["merchant"];
        $param["tradeNum"] = $tradeNum;
        //$param["oTradeNum"] = $_POST["oTradeNum"];
        $param["tradeType"] = 0;// 1表示退款，0表示消费

        $reqXmlStr = XMLUtil::encryptReqXml($param);
        $url = ConfigUtil::get_val_by_key("wepayServerAggreQueryUrl");

        $httputil = new HttpUtils();
        list ($return_code, $return_content) = $httputil->http_post_data($url, $reqXmlStr);
        $flag = XMLUtil::decryptResXml($return_content, $resData);
        if ($flag) {
            //处理交易状态 tradeType
            return $resData;
        } else {
            return [];
        }
    }

    /**
     * 退款
     * @return
     */
    public function refund()
    {
        $param["version"] = "V2.0";
        $param["merchant"] = $this->config["merchant"];
        $param["tradeNum"] = $_POST["tradeNum"];
        $param["oTradeNum"] = $_POST["oTradeNum"];
        $param["amount"] = $_POST["amount"];
        $param["currency"] = $_POST["currency"];
        $param["tradeTime"] = $_POST["tradeTime"];
        $param["notifyUrl"] = $_POST["notifyUrl"];
        $param["note"] = $_POST["note"];
//        $param["cert"] = $_POST["cert"];
        $param["termInfoId"] = $_POST["termInfoId"];
        $param["device"] = $_POST["device"];
        $reqXmlStr = XMLUtil::encryptReqXml($param);
        $url = ConfigUtil::get_val_by_key("wepayServerAggreRefund");
        $httputil = new HttpUtils();
        list ($return_code, $return_content) = $httputil->http_post_data($url, $reqXmlStr);
        $resData = [];
        $flag = XMLUtil::decryptResXml($return_content, $resData);
        if ($flag) {
            $status = $resData['status'];
            if ($status == "0") {
                $resData['status'] = "处理中";
            } else if ($status == "1") {
                $resData['status'] = "成功";
            } else if ($status == "2") {
                $resData['status'] = "失败";
            }
            return $resData;
        } else {
            return [];
        }
    }

    /**
     * 撤销
     * @return array
     */
    public function close()
    {
        $param["version"] = "V2.0";
        $param["merchant"] = $this->config["merchant"];
        $param["tradeNum"] = $_POST["tradeNum"];
        $param["oTradeNum"] = $_POST["oTradeNum"];
        $param["amount"] = $_POST["amount"];
        $param["currency"] = $_POST["currency"];
        $param["tradeTime"] = $_POST["tradeTime"];
        $param["note"] = $_POST["note"];

        $reqXmlStr = XMLUtil::encryptReqXml($param);
        $url = ConfigUtil::get_val_by_key("wepayServerAggreRevoke");
        $httputil = new HttpUtils();
        list ($return_code, $return_content) = $httputil->http_post_data($url, $reqXmlStr);
        $resData = [];
        $flag = XMLUtil::decryptResXml($return_content, $resData);
        if ($flag) {
            $status = $resData['status'];
            if ($status == "0") {
                $resData['status'] = "处理中";
            } else if ($status == "1") {
                $resData['status'] = "成功";
            } else if ($status == "2") {
                $resData['status'] = "失败";
            }
            return $resData;
        } else {
            return [];
        }
    }
}